package cn.javaSong.service.impl;

import cn.javaSong.common.ResponseHelper;
import cn.javaSong.common.ResponseModel;
import cn.javaSong.entity.Video;
import cn.javaSong.mapper.VideoMapper;
import cn.javaSong.service.IVideoService;
import cn.javaSong.utils.StringUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dakai
 * @since 2024-10-26
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements IVideoService {

    @Value("${videoFile}")
    private String videoFile;

    private static final Set<String> VIDEO_EXTENSIONS = new HashSet<>();

    private static final Set<String> VIDEO_MIME_TYPES = new HashSet<>();

    static {
        // 添加常见的视频文件扩展名
        VIDEO_EXTENSIONS.add("mp4");
        VIDEO_EXTENSIONS.add("avi");
        VIDEO_EXTENSIONS.add("mkv");
        VIDEO_EXTENSIONS.add("mov");
        // 添加常见的视频MIME类型
        VIDEO_MIME_TYPES.add("video/mp4");
        VIDEO_MIME_TYPES.add("video/x-msvideo");
        VIDEO_MIME_TYPES.add("video/quicktime");
    }

    @Override
    public ResponseModel addVideo(MultipartFile request) {
        Video video = new Video();
        String mimeType = request.getContentType();
        boolean isMp4ByMimeType = "video/mp4".equalsIgnoreCase(mimeType);
        if (request.isEmpty() || !isMp4ByMimeType) {
            return ResponseHelper.successMessage("请上传一个有效的MP4文件");
        }
        try {
            // 获取文件名
            String fileName = request.getOriginalFilename();
            // 重命名文件名
            String names = StringUtil.getCurrentDateStr() + ".mp4";
            // 创建文件路径
            Path filePath = Paths.get(videoFile + names);
            // 确保目录存在
            File uploadDir = filePath.getParent().toFile();
            video.setUpdateTime(new Date());
            video.setNames(fileName);
            video.setNames(names);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            this.save(video);
            // 保存文件
            Files.write(filePath, request.getBytes());
            return ResponseHelper.successMessage("文件上传成功: " + fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseHelper.successMessage("文件上传失败");
        }
    }
}
